TARGET = cortex-base

LDSCRIPT= lpc1768.ld
MCU = cortex-m3

ifeq ($(shell uname), Linux)
TOOLCH = /home/matthias/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi
TARGET_PATH = /media/matthias/MBED/
else
TOOLCH = "D:/CodeSourcery/Sourcery G++ Lite/bin/arm-none-eabi"
TARGET_PATH = "F:/"
endif

CC = $(TOOLCH)-gcc
OBJCOPY = $(TOOLCH)-objcopy
SIZE = $(TOOLCH)-size

ODIR = .objs
DDIR = .dep
RTOS_DIR = FreeRTOS/Source
HAL_DIR = hal
CONFIG_DIR = config
MODULE_DIR = modules


INCDIRS =  .\
        $(HAL_DIR)/include \
        $(RTOS_DIR)/include \
        $(MODULE_DIR)/include \
        $(RTOS_DIR)/portable/GCC/ARM_CM3 \
        $(CONFIG_DIR) \

# optimization level
DEBUG=stabs 
OPTIM=-O0

# dependency flags
DEPFLAGS = -MD -MP -MF $(DDIR)/$(@F).d

# compiler Flags
CFLAGS  = -g$(DEBUG)
CFLAGS += -D inline= -mthumb 
CFLAGS += -mcpu=$(MCU) $(OPTIM)
CFLAGS += -D PACK_STRUCT_END=__attribute\(\(packed\)\)
CFLAGS += -D ALIGN_STRUCT_END=__attribute\(\(aligned\(8\)\)\)
CFLAGS += -ffunction-sections
CFLAGS += -fdata-sections
CFLAGS += $(patsubst %,-I %,$(INCDIRS))
CFLAGS += -std=gnu99

# compiler warnings
CFLAGS += -Wnested-externs
CFLAGS += -Wmissing-prototypes
CFLAGS += -Wmissing-declarations

# linker Flags
LINKER_FLAGS  = -nostartfiles
LINKER_FLAGS +=	-Xlinker -o$(TARGET).elf
LINKER_FLAGS +=	-Xlinker -M
LINKER_FLAGS +=	-Xlinker -Map=$(TARGET).map
LINKER_FLAGS +=	-Xlinker --gc-sections
LINKER_FLAGS += -lc -lgcc 
LINKER_FLAGS += -lm

# all source files to be compiled
SOURCE= startup.c \
        main.c\
        $(shell echo hal/source/*.c) \
        $(shell echo modules/source/*.c) \
        $(RTOS_DIR)/list.c \
        $(RTOS_DIR)/queue.c \
        $(RTOS_DIR)/tasks.c \
        $(RTOS_DIR)/portable/GCC/ARM_CM3/port.c \
        $(RTOS_DIR)/portable/MemMang/heap_1.c \

# rename object files' folder
_OBJS = $(SOURCE:.c=.o)
OBJS = $(patsubst %,$(ODIR)/%,$(_OBJS))


all: gccversion $(TARGET).bin

#show compiler version
gccversion :
	@$(CC) --version

#create binary
$(TARGET).bin : $(OBJS) 

	# link object files to extended linker file
	$(CC) $(CFLAGS) -T $(LDSCRIPT) $(OBJS) $(LINKER_FLAGS)
		
	# create binary from elf
	$(OBJCOPY) $(TARGET).elf -O binary $(TARGET_PATH)$(TARGET).bin
	
	# show section sizes
	@if [ -f $(TARGET).elf ]; then echo;$(SIZE) -d -A -x $(TARGET).elf ; echo; fi

#create object files
$(ODIR)/%.o : %.c

	#create object folders
	
	@mkdir -p $(dir $@)
	#compile c to object files
	$(CC) -c -o $@ $< $(CFLAGS) $(DEPFLAGS)

#create dependency folder 
include $(shell mkdir $(DDIR) 2>/dev/null) $(wildcard $(DDIR)/*)

#clean up project
clean :
	touch Makefile
	rm -f -r $(OBJS)
	rm $(TARGET).elf
	rm $(TARGET).map
	rm -rf $(ODIR)
	rm -rf $(DDIR)


